package net.bwie.realtime.dwd.douyin.logs.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class IsNewUserOrderFunction extends KeyedProcessFunction<String,String,String> {
    private transient ValueState<Integer> isNewUserOrderState;

    @Override
    public void open(Configuration parameters) throws Exception {
        isNewUserOrderState=
                getRuntimeContext().getState(new ValueStateDescriptor<Integer>("is_first_order",Integer.class));
    }

    @Override
    public void processElement(String s, Context ctx, Collector<String> out) throws Exception {
        //解析json数据
        JSONObject jsonObject = JSON.parseObject(s);

        //获取事件类型
        String event_type = jsonObject.getString("event_type");
        if (event_type!=null && event_type.equals("下单")){
            if (isNewUserOrderState.value()==null){
                jsonObject.put("is_first_order",1);
                isNewUserOrderState.update(1);
            }else {
                jsonObject.put("is_first_order",0);
            }
        }
        out.collect(jsonObject.toJSONString());
    }
}
